﻿using System.Reflection;
using System.Transactions;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using NiuX.AspNetCore.Infrastructure.Filters.Attributes;

namespace NiuX.AspNetCore.Infrastructure.Filters;

/// <summary>
/// 事务过滤器
/// </summary>
public class TransactionScopeFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var disableTransaction = false;

        if (context.ActionDescriptor is ControllerActionDescriptor actionDesc)
        {
            disableTransaction = actionDesc.MethodInfo.IsDefined(typeof(DisableTransactionalAttribute));
        }

        if (disableTransaction)
        {
            await next();
            return;
        }

        using var txScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
        var result = await next();

        if (result.Exception == null)
        {
            txScope.Complete();
        }
    }

}

// Sample

//builder.Services.Configure<MvcOptions>(options =>
//{
//    options.Filters.Add<TransactionScopeFilter>();
//});